<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;

use Illuminate\Database\Eloquent\Factories\HasFactory;
// use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends BaseModel
implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail;
    use HasApiTokens, HasFactory, Notifiable;
    protected $guarded = [];
    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    // protected $fillable = [
    //     'name',
    //     'email',
    //     'password',
    // ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function scopeRelatedJoin($query)
    {
    }
    //search condition
    public function scopeSearch($query, &$search)
    {
        if (isset($search['name']))
            $query->where('name', 'like', '\'%' . $search['name'] . '%\'');
        parent::scopeSearch($query, $search);
        return $query;
    }
    public function rolesList()
    {
        return  $this->hasMany(RoleList::class, "childrenuser_id", "id");
    }


    public function saveitems($items)
    {
        $role_ids = $this->rolesList()->pluck('id', 'id')->toArray();
        foreach ($items as $v) {

            if (isset($v['id']) && (int)$v['id'] > 0) {
                if (isset($role_ids[$v['id']])) {

                    RoleList::where("id", $v['id'])->update($v);
                    unset($role_ids[$v['id']]);
                } else
                    throwError("保存角色所属时参数错误！");
            } else {
                $v['childrenuser_id'] = $this->id;
                //存在，就不保存
                if (!RoleList::where(["childrenuser_id" => $this->id, "role_id" => $v['role_id']])->exists())
                    RoleList::create(array_filter($v));
            }
        }
        //删除已经不存在的
        foreach (RoleList::whereIn("id", $role_ids)->get() as $v) {
            $v->delete();
        };
    }
    public function _deleting()
    {
        foreach ($this->rolesList()->get() as $k => $v) {
            $v->delete();
        }
    }

    public function hasPermission()
    {
        return $this->isAdmin() ? true : RolePermission::whereIn("role_id", $this->getRoles())->where("controller_id", RoleBasedAccessControl::getAccessID())->exists();
    }
    public function isAdmin()
    {
        return in_array(1, $this->getRoles());
    }
    public function getRoles()
    {

        $roleids = $this->rolesList()->pluck('role_id', 'role_id')->toArray();

        //findAllChildIdArray($needarray, $parentids,$parentidstr = "parentid", $idstr = "id")
        $roleArray = RoleList::where("childrenrole_id", ">", "0")->get()->toArray();
        //逆向查找权限
        $roleAllIds = findAllChildIdArray($roleArray, $roleids, 'childrenrole_id', 'role_id');
        return $roleAllIds;
    }
}
